import { Image, List, InfiniteScroll } from "antd-mobile"
// mock数据
// import { users } from "./users"
import { fetchArticleListAPI } from "@/apis/article"
import { useEffect, useState } from "react"
import type { ArticleListRes } from "@/apis/article"
import { useNavigate } from "react-router-dom"

type Props = {
	channelId: string
}
const HomeList = (props: Props) => {
	const { channelId } = props

	const navigate = useNavigate()

	const [articleRes, setArticleRes] = useState<ArticleListRes>({
		results: [],
		pre_timestamp: "" + new Date().getTime(),
	})
	// 开关，标记当前是否还有新数据
	// 上拉加载的触发条件：1、hasMore为true；2、底部的边距小于threshold
	const [hasMore, setHasMore] = useState<boolean>(true)

	// 上拉加载函数
	const loadMore = async () => {
		// 加载新数据
		console.log("loadMore")
		try {
			const res = await fetchArticleListAPI({
				channel_id: channelId,
				timestamp: "" + articleRes.pre_timestamp,
			})
			// 拼接新数据+下一次请求的时间戳
			setArticleRes({
				results: [...articleRes.results, ...res.data.data.results],
				pre_timestamp: res.data.data.pre_timestamp,
			})
			// 停止监听
			if (res.data.data.results.length === 0) {
				setHasMore(false)
			}
		} catch (error) {
			console.log(error)
			throw new Error("fetch article list error")
		}
	}

	const handleClick = (art_id: string) => {
		// 跳转到详情页
		navigate("/detail?id=" + art_id)
	}

	useEffect(() => {
		const getArticleList = async () => {
			try {
				const res = await fetchArticleListAPI({
					channel_id: channelId,
					timestamp: "" + new Date().getTime(),
				})
				setArticleRes({
					results: res.data.data.results,
					pre_timestamp: res.data.data.pre_timestamp,
				})
			} catch (error) {
				console.log(error)
				throw new Error("fetch article list error")
			}
		}
		getArticleList()
	}, [channelId])

	return (
		<>
			<List>
				{articleRes.results.map((item) => (
					<List.Item
						key={item.art_id}
						prefix={
							<Image
								src={item.cover.images?.[0]}
								style={{ borderRadius: 20 }}
								fit="cover"
								width={40}
								height={40}
							/>
						}
						description={item.pubdate}
						arrowIcon={false}
						onClick={() => handleClick(item.art_id)}
					>
						{item.title}
					</List.Item>
				))}
			</List>
			<InfiniteScroll
				loadMore={loadMore}
				hasMore={hasMore}
				threshold={10}
			/>
		</>
	)
}

export default HomeList
